import { useGuessList } from '@/composables'
import { OrderState, orderStateList } from '@/services/constants'
import {
  deleteMemberOrderAPI,
  getMemberOrderByIdAPI,
  getMemberOrderCancelByIdAPI,
  getMemberOrderLogisticsByIdAPI,
  getMemberOrderConsignmentByIdAPI,
  putMemberOrderReceiptByIdAPI,
} from '@/services/order'
import type { LogisticItem, OrderResult } from '@/types/order'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import { getPayMockAPI, getPayWxPayMiniPayAPI } from '@/services/pay'

const useDetailHooks = () => {
  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync()
  // 猜你喜欢
  const { guessRef, onScrolltolower } = useGuessList()
  // 弹出层组件
  const popupRef = ref()
  // 取消原因列表
  const reasonList = ref([
    '商品无货',
    '不想要了',
    '商品信息填错了',
    '地址信息填写错误',
    '商品降价',
    '其它',
  ])
  // 订单取消原因
  const reason = ref('')
  // 复制内容
  const onCopy = (id: string) => {
    // 设置系统剪贴板的内容
    uni.setClipboardData({ data: id })
  }
  // 获取页面参数
  const query = reactive<{
    id: string
  }>({ id: '' })

  // 获取页面栈
  const pages = getCurrentPages()

  // 基于小程序的 Page 类型扩展 uni-app 的 Page
  type PageInstance = Page.PageInstance & WechatMiniprogram.Page.InstanceMethods<any>

  // #ifdef MP-WEIXIN
  // 获取当前页面实例，数组最后一项
  const pageInstance = pages.at(-1) as PageInstance

  // 页面渲染完毕，绑定动画效果
  onReady(() => {
    // 动画效果,导航栏背景色
    pageInstance.animate(
      '.navbar',
      [{ backgroundColor: 'transparent' }, { backgroundColor: '#f8f8f8' }],
      1000,
      {
        scrollSource: '#scroller',
        timeRange: 1000,
        startScrollOffset: 0,
        endScrollOffset: 50,
      },
    )
    // 动画效果,导航栏标题
    pageInstance.animate('.navbar .title', [{ color: 'transparent' }, { color: '#000' }], 1000, {
      scrollSource: '#scroller',
      timeRange: 1000,
      startScrollOffset: 0,
      endScrollOffset: 50,
    })
    // 动画效果,导航栏返回按钮
    pageInstance.animate('.navbar .back', [{ color: '#fff' }, { color: '#000' }], 1000, {
      scrollSource: '#scroller',
      timeRange: 1000,
      startScrollOffset: 0,
      endScrollOffset: 50,
    })
  })
  // #endif

  // 获取订单详情
  const order = ref<OrderResult>()
  const getMemberOrderByIdData = async () => {
    const res = await getMemberOrderByIdAPI(query.id)
    order.value = res.result
    if (
      [OrderState.DaiShouHuo, OrderState.DaiPingJia, OrderState.YiWanCheng].includes(
        order.value.orderState,
      )
    ) {
      getMemberOrderLogisticsByIdData()
    }
  }

  // 获取物流信息
  const logisticList = ref<LogisticItem[]>([])
  const getMemberOrderLogisticsByIdData = async () => {
    const res = await getMemberOrderLogisticsByIdAPI(query.id)
    logisticList.value = res.result.list
  }

  // 倒计时结束事件
  const onTimeup = () => {
    // 修改订单状态为已取消
    order.value!.orderState = OrderState.YiQuXiao
  }

  // 订单支付
  const onOrderPay = async () => {
    if (import.meta.env.DEV) {
      // 开发环境模拟支付
      await getPayMockAPI({ orderId: query.id })
    } else {
      // #ifdef MP-WEIXIN
      // 正式环境微信支付
      const res = await getPayWxPayMiniPayAPI({ orderId: query.id })
      await wx.requestPayment(res.result)
      // #endif

      // #ifdef H5 || APP-PLUS
      // H5端 和 App 端未开通支付-模拟支付体验
      await getPayMockAPI({ orderId: query.id })
      // #endif
    }
    // 关闭当前页，再跳转支付结果页
    uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${query.id}` })
  }

  // 是否为开发环境
  const isDev = import.meta.env.DEV
  // 模拟发货
  const onOrderSend = async () => {
    if (isDev) {
      await getMemberOrderConsignmentByIdAPI(query.id)
      uni.showToast({ icon: 'success', title: '模拟发货完成' })
      // 主动更新订单状态
      order.value!.orderState = OrderState.DaiShouHuo
    }
  }
  // 确认收货
  const onOrderConfirm = () => {
    // 二次确认弹窗
    uni.showModal({
      content: '为保障您的权益，请收到货并确认无误后，再确认收货',
      confirmColor: '#27BA9B',
      success: async (success) => {
        if (success.confirm) {
          const res = await putMemberOrderReceiptByIdAPI(query.id)
          // 更新订单状态
          order.value = res.result
        }
      },
    })
  }
  // 删除订单
  const onOrderDelete = () => {
    // 二次确认
    uni.showModal({
      content: '是否删除订单',
      confirmColor: '#27BA9B',
      success: async (success) => {
        if (success.confirm) {
          await deleteMemberOrderAPI({ ids: [query.id] })
          uni.redirectTo({ url: '/pagesOrder/list/list' })
        }
      },
    })
  }

  // 取消订单
  const onOrderCancel = async () => {
    // 发送请求
    const res = await getMemberOrderCancelByIdAPI(query.id, { cancelReason: reason.value })
    // 更新订单信息
    order.value = res.result
    // 关闭弹窗
    popupRef.value?.close!()
    // 轻提示
    uni.showToast({ icon: 'none', title: '订单取消成功' })
  }

  onLoad((options) => {
    query.id = options!.id
    getMemberOrderByIdData()
  })

  return {
    safeAreaInsets,
    pages,
    onScrolltolower,
    order,
    OrderState,
    onTimeup,
    onOrderPay,
    orderStateList,
    query,
    isDev,
    onOrderSend,
    logisticList,
    onOrderConfirm,
    onCopy,
    popupRef,
    onOrderDelete,
    reasonList,
    reason,
    onOrderCancel,
    guessRef,
  }
}

export default useDetailHooks
